import { useLocalStorage } from '@peng_kai/kit/libs/vueuse';
import { useList } from '~comp-b/global-popups/invitation/hooks';
import { useAuthed } from '~/composables/useAuthed';
import { useFingerprint } from '~/composables/useFingerprint';

const { invitedSpinShow } = useFirstRechargeTips();

interface AutoDisplayUser {
  uid: string;
  nextDisplayTime: number;
}

interface IStorage {
  autoDisplayUsers: AutoDisplayUser[];
  firstDraw?: boolean;
  jump?: boolean;
}

interface PopupConfig {
  code: string; // 弹窗的唯一标识符
  conditions?: any; // 自定义条件判断函数
}

interface Config {
  [key: string]: PopupConfig;
}

const currentPopupCode = ref('');
const currentPopupIndex = ref<number | undefined>(undefined);
const currentPopupConfigs = ref<PopupConfig[] | []>([]);
const { deletePopup } = useAutoPopupController();
const config: Config = {
  luckySpin: {
    code: 'luckySpin',
    conditions: () => (globalPopups.lottery.open?.()),
  },
  invitedSpin: {
    code: 'invitedSpin',
    conditions: () => (globalPopups.invitationSpin.open?.()),
  },
  attendance: {
    code: 'attendance',
    conditions: () => (globalPopups.attendance.open?.()),
  },
  newUserAward: {
    code: 'newUserAward',
    conditions: () => (globalPopups.newUserAward.open?.({ activeType: 'pwa', noticeId: 0 })),
  },
  // 邀请转盘的中奖提示
  invitedSpinTips: {
    code: 'invitedSpinTips',
    conditions: () => {
      invitedSpinShow.value = true;
      deletePopup('invitedSpinTips');
    },
  },
};
const bp = useAppBreakpoints();
function usePwaQueries() {
  const pwaQueries = useQuery({
    queryKey: [apis.apiActivityInstallPwa.id],
    queryFn: () => apis.apiActivityInstallPwa(undefined),
  });
  const pwaData = computed(() => pwaQueries.data?.value);
  return {
    pwaData,
  };
}
// 定期弹窗内容
export async function usePeriodicPopup(bonuses: Ref<any>) {
  const { userInfo } = storeToRefs(useUserStore());
  const authed = useAuthed();
  const route = useRoute();
  const { status } = useList();
  const { pwaData } = usePwaQueries();
  const { pushPopup } = useAutoPopupController();
  const { luckySpinFirstTipsState } = useFirstRechargeTips();
  const luckyspinStorage = useLocalStorage <IStorage >('luckyspin', { autoDisplayUsers: [] });
  const invitedStorage = useLocalStorage<IStorage >('invitedSpin', { autoDisplayUsers: [], firstDraw: false, jump: false }, { mergeDefaults: true });
  const firstRechargeStorage = useLocalStorage <IStorage >(' firstRecharge', { autoDisplayUsers: [] });
  const pawStorage = useLocalStorage<IStorage >('installPwaActive', { autoDisplayUsers: [] });
  useLocalStorage('firstGiveaway', { firstDraw: false }, { mergeDefaults: true });

  const { getDeviceInfoMD5 } = useFingerprint(false);
  const device = await getDeviceInfoMD5();
  const luckyspinUserIndex = computed(() => luckyspinStorage.value.autoDisplayUsers.findIndex(x => x.uid === (userInfo.value?.uid ?? '')));
  const invitedDeviceIndex = computed(() => invitedStorage.value.autoDisplayUsers.findIndex(x => x.uid === (device ?? '')));
  const luckyspinDeviceIndex = computed(() => luckyspinStorage.value.autoDisplayUsers.findIndex(x => x.uid === (device ?? '')));
  const invitedUserIndex = computed(() => invitedStorage.value.autoDisplayUsers.findIndex(x => x.uid === (userInfo.value?.uid ?? '')));
  const firstRechargeUserIndex = computed(() => firstRechargeStorage.value.autoDisplayUsers.findIndex(x => x.uid === (userInfo.value?.uid ?? '')));
  // 转盘自动显示 todo 旧转盘不再需要自动弹出
  // const stop = watch(bonuses, async (current) => {
  //   if (!userInfo.value?.uid)
  //     return;
  //
  //   const inviter = invitionSpinActive(current);
  //   const lucky = luckySpinActive(current);
  //   const rechar = firstRechargeActive(current);
  //
  //   Promise.all([inviter, lucky, rechar]).then(() => {
  //     stop();
  //   });
  // }, { deep: true, immediate: true });

  // 小小充值提示首次充值奖励
  function firstRechargeActive(current: any) {
    const item = {
      uid: userInfo.value?.uid,
      nextDisplayTime: (new Date()).getTime() + 24 * 60 * 60 * 1000,
    };
    if ((firstRechargeStorage.value.autoDisplayUsers?.length === 0
      || firstRechargeUserIndex.value === -1
      || firstRechargeStorage.value.autoDisplayUsers?.[firstRechargeUserIndex.value].nextDisplayTime < (new Date()).getTime())
      && Number(current?.signup?.amount)
    ) {
      if (firstRechargeUserIndex.value === -1) {
        firstRechargeStorage.value.autoDisplayUsers?.push(item);
      }
      else {
        firstRechargeStorage.value.autoDisplayUsers[firstRechargeUserIndex.value] = item;
      }

      if (userInfo.value?.auto_lucky_spin) {
        luckySpinFirstTipsState.initial = true;
      }
    }
    return Promise.resolve();
  }

  // 邀请转盘活动
  function invitionSpinActive(current: any) {
    const item = {
      uid: userInfo.value?.uid,
      nextDisplayTime: (new Date()).getTime() + 24 * 60 * 60 * 1000,
    };
    if ((invitedStorage.value.autoDisplayUsers?.length === 0
      || invitedUserIndex.value === -1
      || invitedStorage.value.autoDisplayUsers?.[invitedUserIndex.value].nextDisplayTime < (new Date()).getTime())
      && current?.hasOwnProperty?.('invitespin')
      && current.invitespin.available
    ) {
      if (invitedUserIndex.value === -1) {
        invitedStorage.value.autoDisplayUsers?.push(item);
      }
      else {
        invitedStorage.value.autoDisplayUsers[invitedUserIndex.value] = item;
      }
      if (bp.tabletl || route.name !== 'invitation') {
        pushPopup('invitedSpin');
        pushPopup('invitedSpinTips');
      }
    }
    return Promise.resolve();
  }

  // 幸运转盘活动
  function luckySpinActive(current: any) {
    const item = {
      uid: userInfo.value?.uid,
      nextDisplayTime: (new Date()).getTime() + 24 * 60 * 60 * 1000,
    };

    if ((luckyspinStorage.value.autoDisplayUsers?.length === 0
      || luckyspinUserIndex.value === -1
      || luckyspinStorage.value.autoDisplayUsers?.[luckyspinUserIndex.value].nextDisplayTime < (new Date()).getTime())
      && current?.luckyspin?.available
      && !current?.hasOwnProperty?.('invitespin')
    ) {
      if (luckyspinUserIndex.value === -1) {
        luckyspinStorage.value.autoDisplayUsers?.push(item);
      }
      else {
        luckyspinStorage.value.autoDisplayUsers[luckyspinUserIndex.value] = item;
      }
      pushPopup('luckySpin');
      pushPopup('attendance');
    }
    return Promise.resolve();
  }

  // 初始化-邀请转盘
  watch([status, pwaData], async ([current, pwa]) => {
    if (!authed.value && current?.available && current?.count !== 0) {
      await initInvitedSpin();
    }
    if (pwa && pwa?.available) {
      await initInstallAllPWAActive();
    }
    // if (!authed.value && status.value?.available === false) {
    //   await initLuckySpin();
    // }
  });

  function initLuckySpin() {
    const item = {
      uid: device,
      nextDisplayTime: (new Date()).getTime() + 24 * 60 * 60 * 1000,
    };
    if ((luckyspinStorage.value.autoDisplayUsers.length === 0
      || toValue(luckyspinDeviceIndex) === -1
      || luckyspinStorage.value.autoDisplayUsers[toValue(luckyspinDeviceIndex)].nextDisplayTime < (new Date()).getTime())
    ) {
      if (toValue(luckyspinDeviceIndex) === -1) {
        luckyspinStorage.value.autoDisplayUsers.push(item);
      }
      else {
        luckyspinStorage.value.autoDisplayUsers[toValue(luckyspinDeviceIndex)] = item;
      }
      pushPopup('luckySpin');
      return Promise.resolve();
    }
  }

  function initInvitedSpin() {
    const item = {
      uid: device,
      nextDisplayTime: (new Date()).getTime() + 24 * 60 * 60 * 1000,
    };
    //  未登录，并且开启活动
    if ((invitedStorage.value?.autoDisplayUsers?.length === 0
      || invitedDeviceIndex.value === -1
      || invitedStorage.value.autoDisplayUsers[invitedDeviceIndex.value]?.nextDisplayTime < (new Date()).getTime())
    ) {
      if (invitedDeviceIndex.value === -1) {
        invitedStorage.value.autoDisplayUsers?.push(item);
      }
      else {
        invitedStorage.value.autoDisplayUsers[invitedDeviceIndex.value] = item;
      }
      if (bp.tabletl || route.name !== 'invitation') {
        pushPopup('invitedSpin');
        pushPopup('invitedSpinTips');
      }
    }
    return Promise.resolve();
  }

  function initInstallAllPWAActive() {
    const item = {
      uid: device,
      nextDisplayTime: 0,
    };
    //  未登录，并且开启活动
    if ((pawStorage.value?.autoDisplayUsers?.length === 0)) {
      pawStorage.value.autoDisplayUsers?.push(item);
      pushPopup('newUserAward');
    }
    return Promise.resolve();
  }
}

// 自动弹窗控制器
export function useAutoPopupController() {
  function pushPopup(code: string) {
    currentPopupConfigs.value.push(config[code]);
  };
  function deletePopup(code: string) {
    const index = currentPopupConfigs.value.findIndex(item => item.code === code);
    if (index > -1) {
      currentPopupConfigs.value.splice(index, 1);
    }
  }

  watch(() => currentPopupConfigs, (c: Ref<PopupConfig[]>) => {
    console.log('c', c);
    c.value[0]?.conditions?.();
    currentPopupCode.value = c.value[0]?.code;
    currentPopupIndex.value = 0;
  }, { deep: true });

  return {
    pushPopup,
    deletePopup,
  };
}
